//
//  QXEmoticon.swift
//  图文混排
//
//  Created by QinXin on 15/7/7.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit

/**
    说明：
    1、emoticons.plist （根目录）： 保存了表情包的信息
        packages 是一个数组 ， 里面的 id 是分组路径名称
    2、在每个分组内都有一个 info.plist
        group_name_cn： 分组名称
        emoticons： 表情数组
*/

class QXEmoticonPackage: NSObject {
    
    /// 表情路径
    var id: String?
    /// 分组名称
    var groupName: String?
    
    var emoticons: [QXEmoticon]?
    
    init(id: String) {
        self.id = id
    }
    
    func addFavoriteEmoticon(emoticon: QXEmoticon) {
        
        // 判断已经包含
        if !emoticons!.contains(emoticon) {
            emoticons?.append(emoticon)
            // 排序,并删除末尾
            var res = emoticons!
            res = res.sort { $0.useCount > $1.useCount }
            res.removeLast()
            emoticons = res
        }
    }
    
    class func packages() -> [QXEmoticonPackage] {
        
        var pkgs = [QXEmoticonPackage]()
        
        // 最近使用的数组
        let p = QXEmoticonPackage(id: "")
        p.groupName = "最近"
        pkgs.append(p)
        p.appendEmptyEmoticons()
        
        // 载入emoticons.plist
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
        let dic = NSDictionary(contentsOfFile: path)!
        
        let arr = dic["packages"] as! [[String: AnyObject]]
        
        for d in arr {
            let p = QXEmoticonPackage(id: d["id"] as! String)
            p.loadEmoticons()
            p.appendEmptyEmoticons()
            pkgs.append(p)
        }
        
        return pkgs
    }
    
    
    private func loadEmoticons() {
        
        // 加载 id 路径对应的 info.plist
        let dic = NSDictionary(contentsOfFile: plistPath())!
        groupName = dic["group_name_cn"] as? String
        let arr = dic["emoticons"] as! [[String: String]]
        emoticons = [QXEmoticon]()
        var idx = 0
        for d in arr {
            emoticons?.append(QXEmoticon(id: id, dic: d))
            idx++
            if idx == 20 {
                emoticons?.append(QXEmoticon(isRemoveBtn: true))
                idx = 0
            }
        }
                
    }
    
    private func appendEmptyEmoticons() {
        
        if emoticons == nil {
            emoticons = [QXEmoticon]()
        }
        
        let count = emoticons!.count % 21

        if count > 0 || emoticons!.count == 0 {
            for _ in count..<20 {
                emoticons?.append(QXEmoticon(isRemoveBtn: false))
            }
            emoticons?.append(QXEmoticon(isRemoveBtn: true))
            
        }
        
    }
    
    /// 取得表情包的路径
    private class func bundlePath() -> String {
        return NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons.bundle")
    }
    
    /// 返回表情路径
    private func plistPath() -> String {
        return QXEmoticonPackage.bundlePath().stringByAppendingPathComponent(id!).stringByAppendingPathComponent("info.plist")
    }
    
    
}

class QXEmoticon: NSObject {
    /// 路径
    var id: String?
    /// 表情文字
    var chs: String?
    /// 图片
    var png: String?
    /// 编码
    var code: String? {
        didSet {
            // 通过扫描器转换为 uint
            let scaner = NSScanner(string: code!)
            var res: UInt32 = 0
            scaner.scanHexInt(&res)
            // 再转换为unicode
            emoji = "\(Character(UnicodeScalar(res)))"
        }
    }
    
    /// 图片的完整路径
    var imagePath: String? {
        return png == nil ? nil : QXEmoticonPackage.bundlePath().stringByAppendingPathComponent(id!).stringByAppendingPathComponent(png!)
    }
    
    var emoji: String?
    var isRemoveBtn = false
    
    var useCount = 0
    
    init(isRemoveBtn: Bool) {
        self.isRemoveBtn = isRemoveBtn
    }
    
    init(id: String?, dic: [String: String]) {
        super.init()
        self.id = id

        setValuesForKeysWithDictionary(dic)
        
        
    }
    
    // 这个KVC 方法会过滤掉 没定义的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    

}
